﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SysCommon
{
   public static class CurrencyRate
    {
        /// <summary>
        /// 汇率转换
        /// </summary>
        /// <param name="Currency">当前币种：CNY</param>
        /// <param name="ToCurrency">目标币种:USD</param>
        /// <returns>汇率</returns>
       public static decimal GetExchangeRate(string Currency, string ToCurrency = "CNY")
        {

            int Number = 0;
        one:
            string Price = null;
            string url = string.Format("http://hk.finance.yahoo.com/q/bc?s={0}=X&t=5d&l=on&z=m&q=l&c=", Currency + ToCurrency);
            System.Net.WebRequest request = System.Net.WebRequest.Create(url);
            request.Method = "Get";
            request.ContentType = "application/x-www-form-urlencoded";
            try
            {
                using (System.Net.WebResponse response = request.GetResponse())
                {
                    using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        string str = reader.ReadToEnd();
                        if (!string.IsNullOrEmpty(str))
                            Price = str.Substring(str.IndexOf("<span class=\"time_rtq_ticker\"") + 30, 5);
                    }
                }
            }
            catch (Exception)
            {
                if (Number == 0)
                {
                    Number++;
                    goto one;
                }
            }
            return Convert.ToDecimal(Price);
        }
    }
}
